from django.conf import settings
from django.shortcuts import render
from django.views import View
from rest_framework.views import APIView
from django.http import JsonResponse
import random
# Create your views here.
from rest_framework.generics import RetrieveUpdateAPIView
from rest_framework.generics import CreateAPIView, UpdateAPIView
from apps.questions.models import Reply
from apps.users.serializers import RegisterUserSerializer, UserSerializer, \
    UserLabelSerializer, UserPwdSerializer
from rest_framework.response import Response
from django_redis import get_redis_connection
from celery_tasks.sms.tasks import celery_send_sms_code
from utils.fastdfs.fastdfs_storage import MyStorage
import re

class SMSCodesAPIView(APIView):
    """发送短信"""

    def get(self, request, mobile):
        # 创建连接到redis的对象
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'success': False,
                                 'sms_code': 'None',
                                 'message': '手机号格式不正确'
                                 })
        redis_conn = get_redis_connection('code')

        sms_code = redis_conn.get('send_flag_%s' % mobile)
        if sms_code:
            return JsonResponse({'success': False,
                                 'sms_code': 'None',
                                 'message': '请求短信频繁'
                                 })

        #  生成短信验证码：生成6位数验证码
        sms_code = '%06d' % random.randint(0, 999999)
        print('短信验证码:', sms_code)

        # 保存短信验证码
        # 短信验证码有效期，单位：300秒
        # redis管道
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, 300, sms_code)

        pl.setex("send_flag_%s" % mobile, 60, 1)
        # 执行命令
        pl.execute()

        # 荣联运发送短信
        celery_send_sms_code.delay(mobile, sms_code)

        # 响应结果
        return JsonResponse({'success': True,
                             # 'sms_code': sms_code,
                             # 'message': 'OK'
                             })


class RegisterUserAPIView(CreateAPIView):
    """注册"""
    serializer_class = RegisterUserSerializer


class UserDetailView(RetrieveUpdateAPIView):
    """个人中心"""
    serializer_class = UserSerializer

    def get_object(self):
        user = self.request.user
        reply = Reply.objects.filter(user_id=user.id)
        user.answer_question = []
        for item in reply:
            if item.type == 2:
                user.answer_question.append(item)
        return user


class UpdatePwdView(UpdateAPIView):
    # 更新密码
    serializer_class = UserPwdSerializer

    def get_object(self):
        return self.request.user


class UpdateLabelView(UpdateAPIView):
    # 擅长技术
    serializer_class = UserLabelSerializer

    def get_object(self):
        return self.request.user


class UploadImageView(APIView):
    """上传头像"""

    def post(self, request):
        storage = MyStorage()
        img_url = storage._save('', request.FILES.get('img'))
        result_url = settings.FDFS_URL + img_url

        return Response({
            'imgurl': result_url
        })
